﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Shared
{
    using SharingCenter.Web.Classes;
    using ClassLibrary.ContactRetriever;
    using System.Net.Mail;
    using SharingCenter.Web.Classes.Message;
    using System.Collections.Specialized;
    using WindowsLive;

    public partial class GetContactsAndSendMail : SharedUserControl
    {
        public string MailSubject { get; set; }
        public string VariableMailContent { get; set; }
        public string FixedMailContent { get; set; }
        public string ContectEmailReplacementKey { get; set; }
        public Guid UserId { get; set; }
        static WindowsLiveLogin wll = new WindowsLiveLogin(true);
        protected WindowsLiveLogin.ConsentToken Token;
        protected string ConsentUrl;
        public string SendCompleteText { get; set; }
        public string ReturnUrl { get; set; }
        public bool DefaultManual { get; set; }


        protected void Page_Init(object sender, EventArgs e)
        {
            Wizard1.ActiveStepChanged += new EventHandler(Wizard1_ActiveStepChanged);
            lvSelectedContacts.DataBound += new EventHandler(lvSelectedContacts_DataBound);
            rdoManual.CheckedChanged += new EventHandler(rdoManual_CheckedChanged);
            if (!IsPostBack)
            {
                Session["SELECTED_CONTACTS"] = null;
                if (Request.Cookies["lid"] != null)
                {
                    HttpCookie myCookie = new HttpCookie("lid");
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                    Response.Cookies.Add(myCookie);
                }
            }
            
        }

        void rdoManual_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoManual.Checked)
            {
                Wizard1.ActiveStepIndex = 2;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ConsentUrl = wll.GetConsentUrl("Contacts.View", UserId.ToString());
            if (!IsPostBack && DefaultManual)
            {
                Wizard1.ActiveStepIndex = 2;
            }
        }

        void lvSelectedContacts_DataBound(object sender, EventArgs e)
        {
            ltrSelectCount.Text = lvSelectedContacts.Items.Count.ToString();
        }

        void Wizard1_ActiveStepChanged(object sender, EventArgs e)
        {
            switch (Wizard1.ActiveStepIndex)
            {
                case 1:
                    GetContacts();
                    break;
                case 2:
                    SaveSelectedContacts();
                    break;
                case 3:
                    SendMail();
                    break;
                default: break;
            }
        }

        void ConcatExtraContacts(ref List<MailAddress> selected)
        {
            if (selected == null) selected = new List<MailAddress>();
            char[] s = { '|' };
            char[] es = { ',' };
            string[] entries = hdnExtraContacts.Value.Split(s);
            foreach (string entry in entries)
            {
                string e = entry.Trim();
                if (e != string.Empty)
                {
                    string[] c = e.Split(es);
                    selected.Add(new MailAddress(c[1], c[0]));
                }
            }
        }

        private void SendMail()
        {
            List<MailAddress> selectedAddress = (List<MailAddress>)Session["SELECTED_CONTACTS"];
            ConcatExtraContacts(ref selectedAddress);
            IMessage msg = new SiteMailMessage();

            foreach (MailAddress addr in selectedAddress)
            {
                Dictionary<string, string> rep = new Dictionary<string, string>();
                try
                {
                    rep.Add("ContactEmail", addr.Address);
                    msg.SendSystemMail(txtMailSubject.Text.Trim(), txtMailContent.Text + Environment.NewLine + lblFixedContent.Text, addr.Address, rep);
                }
                catch
                {
                    //mvComplete.ActiveViewIndex = 1;
                }
            }
        }

        private void SaveSelectedContacts()
        {
            List<MailAddress> selectedAddresses = new List<MailAddress>();
            foreach (ListViewDataItem item in lvContacts.Items)
            {
                CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
                if (chk.Checked)
                {
                    string emailAddress = ((Label)item.FindControl("lblEmail")).Text;
                    selectedAddresses.Add(new MailAddress(emailAddress, chk.Text == "---" ? "" : chk.Text));
                }
            }

            Session["SELECTED_CONTACTS"] = selectedAddresses;
            lvSelectedContacts.DataSource = selectedAddresses;
            lvSelectedContacts.DataBind();

            txtMailSubject.Text = MailSubject;
            txtMailContent.Text = VariableMailContent;
            lblFixedContent.Text = FixedMailContent;
        }

        private void GetContacts()
        {
            string provider = string.Empty;
            if (rdoGoogle.Checked)
            {
                provider = "google";
            }
            else if (rdoLive.Checked)
            {
                provider = "live";
            }
            else if (rdoManual.Checked)
            {
                provider = "manual";
            }

            RetrieveContacts(provider, txtUserName.Text.Trim(), txtPassword.Text);
        }

        private void RetrieveContacts(string provider, string un, string pwd)
        {
            IContactRetriever retriever = null;
            switch (provider.ToLower().Trim())
            {
                case "google":
                    retriever = new GoogleContactRetriever("HQHD_INVITE", un, pwd);
                    break;
                case "live":
                    string lid = string.Empty, delToken = string.Empty;
                    if (Request.Cookies["lid"] != null)
                        lid = Request.Cookies["lid"].Value;
                    if (Request.Cookies["token"] != null)
                        delToken = Request.Cookies["token"].Value;
                    retriever = new LiveContactRetriever(lid, delToken);
                    break;
                case "manual":
                    Wizard1.ActiveStepIndex = 2;
                    break;
                default: break;
            }

            if (retriever != null)
            {
                List<MailAddress> retrieved = retriever.RetrieveContact();
                //lvContacts.DataSource = from t in retrieved.AllKeys
                //                        select new
                //                        {
                //                            Key = t,
                //                            Value = retrieved[t]
                //                        };
                lvContacts.DataSource = retrieved;
                lvContacts.DataBind();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            Panel1.CssClass = CssClass;
        }

        void btnGetContact_Click(object sender, EventArgs e)
        {
            
        }

        protected void lnkReturnUrl_Load(object sender, EventArgs e)
        {
            if (ReturnUrl != "")
            {
                ((HyperLink)sender).NavigateUrl = ReturnUrl;
            }
        }
    }
}